package com.gitee.wsl.reflect

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty


data class CappedValueDelegate<C : Comparable<C>>(
    private var value: C,
    private val lowerBound: () -> C,
    private val lowerBoundVal: () -> C = lowerBound,
    private val upperBound: () -> C,
    private val upperBoundVal: () -> C = upperBound,
    private val updateListener: (C) -> Unit = { }
) : ReadWriteProperty<Any?, C> {

    override fun getValue(thisRef: Any?, property: KProperty<*>): C {
        val oldValue = this.value
        val v1 = if (value > upperBound()) upperBoundVal() else value
        value = if (value < lowerBound()) lowerBoundVal() else v1
        if (oldValue != value) {
            updateListener(value)
        }
        return value
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: C) {
        val oldValue = this.value
        this.value = value
        if (oldValue != value) {
            updateListener(value)
        }
    }
}